from django.db import DatabaseError
from django.shortcuts import render
from django.http import HttpResponse
from django.views import View
from django import http
import json
from user.models import User, Follow
from message.models import Chat, RecentNews
import time


# 注册接口
class Register(View):

    def post(self, request):
        username = json.loads(request.body)['username']
        password = json.loads(request.body)['password']
        phone = json.loads(request.body)['phone']
        if not all([username, password, phone]):
            return http.JsonResponse({"code": "201", "message": "缺少必传参数"})
        count = User.objects.filter(phone=phone).count()
        if count == 1:
            return http.JsonResponse({'code': '202', 'message': '手机号已注册'})
        # try:
        user = User.objects.create(username=username, password=password, phone=phone)
        # except DatabaseError:
        #     return http.JsonResponse({'code': '203', 'message': '用户名已注册'})
        # with open(f'./apps/user/static/imgs/headimg.jpeg', 'rb') as f1:
        #     with open(f'./apps/user/static/headImg/{username}.png', 'wb') as f:
        #         f.write(f1.read())
        #         f.close()
        #     f1.close()
        return http.JsonResponse({'code': '200', 'username': username, 'user_id': user.user_id, 'avatar': user.avatar})


# 登录接口
class Login(View):

    def post(self, request):
        print(request.body)
        phone = json.loads(request.body)['phone']
        password = json.loads(request.body)['password']
        if not all([phone, password]):
            return http.JsonResponse({"code": "201", "message": "缺少必传参数"})
        # 查询用户是否存在
        userCount = User.objects.filter(phone=phone, password=password).count()
        if userCount == 0:
            return http.JsonResponse({'code': '204', 'message': '手机号或密码错误'})
        us = User.objects.values().filter(phone=phone)
        return http.JsonResponse({'code': '200', 'data': list(us)[0]})


# 根据手机号获取某个用户信息
class GetUserMessage(View):

    def get(self, request):
        phone = request.GET.get('phone')
        user_data = User.objects.values().filter(phone=phone)
        return http.JsonResponse({'code': '200', 'data': list(user_data)[0]})


# 根据id获取某个用户信息
class GetIdUserMessage(View):

    def get(self, request):
        user_id = request.GET.get('user_id')
        user_data = list(User.objects.values().filter(user_id=user_id))[0]
        fans_data = list(Follow.objects.values().filter(user_id=user_id))
        follow_data = list(Follow.objects.values().filter(fans_id=user_id))
        user_data["fans"] = []
        for fans in fans_data:
            fans_user_data = list(User.objects.values().filter(user_id=fans["fans_id"]))[0]
            user_data["fans"].append({
                "user_id": fans["fans_id"],
                "mutual_follow": fans["mutual_follow"],
                "username": fans_user_data["username"],
                "avatar": fans_user_data["avatar"],
                "sign": fans_user_data["sign"]
            })
        user_data["follow"] = []
        for follow in follow_data:
            follow_user_data = list(User.objects.values().filter(user_id=follow["user_id"]))[0]
            user_data["follow"].append({
                "user_id": follow["user_id"],
                "mutual_follow": follow["mutual_follow"],
                "username": follow_user_data["username"],
                "avatar": follow_user_data["avatar"],
                "sign": follow_user_data["sign"]
            })
        return http.JsonResponse({'code': '200', 'data': user_data})


# 更新个人信息接口
class UpdateUserMess(View):

    def post(self, request):
        phone = json.loads(request.body)['phone']
        sex = json.loads(request.body)['sex']
        avatar = json.loads(request.body)['avatar']
        sign = json.loads(request.body)['sign']
        username = json.loads(request.body)['username']
        User.objects.filter(phone=phone).update(sex=sex, avatar=avatar, sign=sign, username=username)
        return http.JsonResponse({'code': '200', 'message': '更新成功'})


# 关注接口
class FollowUser(View):

    def post(self, request):
        user_id = json.loads(request.body)['user_id']
        is_follow = json.loads(request.body)['is_follow']
        fans_id = json.loads(request.body)['fans_id']
        follow_data = Follow.objects.values().filter(user_id=fans_id, fans_id=user_id)
        if is_follow:
            if follow_data:
                Follow.objects.create(user_id=user_id, fans_id=fans_id, mutual_follow=True)
                Follow.objects.filter(user_id=fans_id, fans_id=user_id).update(mutual_follow=True)
            else:
                Follow.objects.create(user_id=user_id, fans_id=fans_id, mutual_follow=False)
        else:
            if follow_data:
                Follow.objects.filter(user_id=fans_id, fans_id=user_id).update(mutual_follow=False)
            Follow.objects.filter(user_id=user_id, fans_id=fans_id).delete()

        try:
            Chat.objects.create(from_user_id=user_id, to_user_id=fans_id, chat_content='感谢您的关注',
                                          is_image=False, is_send=True, is_read=True, is_show_time=True)
            Chat.objects.create(from_user_id=fans_id, to_user_id=user_id, chat_content='感谢您的关注',
                                          is_image=False, is_send=False, is_read=False, is_show_time=True)
        except DatabaseError:
            return http.JsonResponse({'code': '207', 'message': '发送失败'})
        recent_news_data_me = RecentNews.objects.values().filter(user_id=user_id, recent_user_id=fans_id)
        recent_news_data_to = RecentNews.objects.values().filter(user_id=fans_id, recent_user_id=user_id)
        if recent_news_data_me:
            RecentNews.objects.filter(user_id=user_id, recent_user_id=fans_id).update(last_msg='感谢您的关注')
        else:
            RecentNews.objects.create(user_id=user_id, recent_user_id=fans_id, last_msg='感谢您的关注')
        if recent_news_data_to:
            RecentNews.objects.filter(user_id=fans_id, recent_user_id=user_id).update(
                last_msg='感谢您的关注')
        else:
            RecentNews.objects.create(user_id=fans_id, recent_user_id=user_id,
                                      last_msg='感谢您的关注')
        return http.JsonResponse({'code': '200', 'message': '成功'})


# 上传图片接口
class UploadImage(View):

    def post(self, request):
        file = request.FILES["file"]
        name = time.time()
        with open(f'./static/image/uploadImg/{name}.png', 'wb') as f:
            f.write(file.file.read())
            f.close()
        return http.JsonResponse({'code': '200', 'url': f"static/image/uploadImg/{name}.png"})

